from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
# from rest_framework.generics import CreateAPIView, RetrieveAPIView
from rest_framework.authentication import SessionAuthentication
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from api.jwt_auth import MyJwtAuthentication
from rest_framework.permissions import AllowAny, IsAuthenticated, IsAuthenticatedOrReadOnly
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.response import Response
from rest_framework import status
from .serializers import *


class UserLoginViewSet(ModelViewSet):
    queryset = User.objects.all()
    authentication_classes = []
    permission_classes = [AllowAny, ]
    serializer_class = UserLoginSerializers
    pagination_class = LimitOffsetPagination

    def get(self, request):
        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        response = {
            'success': 'True',
            'status code': status.HTTP_200_OK,
            'message': 'User logged in  successfully',
            'token': serializer.data['token'],
        }
        status_code = status.HTTP_200_OK

        return Response(response, status=status_code)


class UserRegisterViewSet(ModelViewSet):
    queryset = User.objects.all()
    authentication_classes = []
    permission_classes = [AllowAny, ]
    serializer_class = UserRegisterSerializer
    pagination_class = LimitOffsetPagination

    def post(self, request):
        serializer = self.UserRegisterSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            # status_code = status.HTTP_201_CREATED
            response = {
                'msg': '用户注册成功',
                'next_url': {
                    'url': 'api/jwt-login/',
                    'form-data': {
                        'username': 'username',
                        'password': 'password'
                    }
                }
            }
            return Response(response, status=200)
        return Response(serializer.errors, status=400)


# from rest_framework.views import APIView
# from rest_framework.viewsets import ViewSet
# # from .serializers import UserLoginSerializers, UserRegistrationSerializer
# from .serializers import *
# from rest_framework import status
# from rest_framework.generics import CreateAPIView, RetrieveAPIView
# from rest_framework.response import Response
# from rest_framework.permissions import AllowAny, IsAuthenticated
# from rest_framework_jwt.authentication import JSONWebTokenAuthentication
#
#
# class UserLoginView(RetrieveAPIView):
#     """用户登录,一般采用不显示参数的post方法"""
#     authentication_classes = []
#     permission_classes = [AllowAny, ]
#
#     def post(self, request):
#         serializer = self.UserLoginSerializers(data=request.data)
#         serializer.is_valid(raise_exception=True)
#         response = {
#             'success': 'True',
#             'status code': status.HTTP_200_OK,
#             'message': 'User logged in  successfully',
#             'token': serializer.data['token'],
#             }
#         status_code = status.HTTP_200_OK
#
#         return Response(response, status=status_code)
#
#
# class UserRegisterView(CreateAPIView):
#     # queryset = User.objects.all()
#     authentication_classes = []
#     permission_classes = [AllowAny, ]
#     serializer_class = UserRegisterSerializer
#
#     def post(self, request):
#         serializer = self.UserRegisterSerializer(data=request.data)
#         if serializer.is_valid():
#             serializer.save()
#             # status_code = status.HTTP_201_CREATED
#             response = {
#                 'msg': '用户注册成功',
#                 'next_url': {
#                     'url': 'api/jwt-login/',
#                     'form-data': {
#                         'username': 'username',
#                         'password': 'password'
#                     }
#                 }
#             }
#             return Response(response, status=200)
#         return Response(serializer.errors, status=400)




# get_token函数
# import jwt
# import datetime
# from django.conf import settings
#
#
# def get_token(payload, timeout):
#     salt = settings.SECRET_KEY
#     headers = {
#         "typ": "jwt_",
#         "alg": "HS256",
#     }
#     payload["exp"] = datetime.datetime.utcnow() + datetime.timedelta(minutes=timeout)
#     token = jwt.encode(payload=payload, key=salt, headers=headers).decode("utf-8")
#     return token
#
#
# class UserLoginView(APIView):
#     authentication_classes = []
#
#     def post(self, request, *args, **kwargs):
#         username = request.data.get("username")
#         password = request.data.get("password")
#         # user_obj = models.UserInfo.objects.filter(username=username, password=passwork).first()
#         user_obj = User.objects.filter(username=username, password=password).first()
#         if not user_obj:
#             return Response({"code": 1000, 'error': '用户名或密码错误'})
#         payload = {
#             "id": user_obj.pk,
#             "name": user_obj.username,
#         }
#         token = get_token(payload, 5)
#         return Response({"code": 1001, 'data': token})

